import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker';

import { zkOHOSDevice } from "@ohos/ohosdevice"
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;

/**
 * Defines the event handler to be called when the worker thread receives a message sent by the host thread.
 * The event handler is executed in the worker thread.
 *
 * @param e message data
 */
workerPort.onmessage = function (e: MessageEvents) {
  console.info("onmessage fd=", e.data)
  //workerPort.postMessage("waiting for the worker ....")
  let count = 0;

  const intervalId = setInterval(() => {
    if (e.data > 0) {
      console.info('send to main thread===================res=')
      let dataBuf = new ArrayBuffer(1024);
      let view = new Uint8Array(dataBuf);
      //Hilog.info(`UartTest============================== >2-1`)
      console.info('send to main thread===================res=1')
      let res = zkOHOSDevice.napi_serial_read(e.data, 1024, dataBuf);
      console.info(`UartTest ------------------------> napi_serial_read ${dataBuf}`)
      //Hilog.info(`UartTest ------------------------> napi_serial_read ${res}}`)
      console.info(`UartTest ------------------------> napi_serial_read ${res}`)
      if (res > 0) {
        let hexString = '';
        for (let i = 0; i < res; i++) {
          hexString += view[i].toString(16).padStart(2, '0');
        }
        //到此 hexString 已经是返回的16进制字符串了


        //const stringFromBuf = Array.from(new Uint8Array(dataBuf)).map(chr => String.fromCharCode(chr)).join('');
        //console.log(stringFromBuf);

        console.info(`UartTest ------------------------> napi_serial_read  LEN=${res} DATA= ${hexString}}`)
        //workerPort.postMessage(hexString)
        workerPort.postMessage("---分割线---");
        if(hexString.length == 20 && hexString.indexOf("0142") == 0 && hexString.indexOf("0d") == 18) {
          //称
          let byteArray = [1];
          byteArray = [];
          for (let i = 0; i < hexString.length; i += 2) {
            byteArray.push(Number.parseInt('0x' + hexString.substr(i, 2), 16));
          }
          let x1 = (byteArray[2] & 0x0F) + 0x30;
          let x2 = (byteArray[3] & 0x0F) + 0x30;
          let x3 = (byteArray[4] & 0x0F) + 0x30;
          let x4 = (byteArray[5] & 0x0F) + 0x30;
          let x5 = (byteArray[6] & 0x0F) + 0x30;

          //零点标志 0不在 1在
          let zorepoint = (byteArray[7] >> 0) & 1;
          //超载符号 0未超载 1已超载
          let overload = (byteArray[7] >> 1) & 1;
          //重量符号 0正数 1负数
          let flag = (byteArray[7] >> 2) & 1;
          //稳定标准 0不稳定 1稳定
          let wending = (byteArray[7] >> 3) & 1;

          //计算重量
          let re = (x5 - 0x30) * 65536 + (x4 - 0x30) * 4096 + (x3 - 0x30) * 256 + (x2 - 0x30) * 16 + (x1 - 0x30);
          re = re / 1000;
          //保留后三位 单位公斤
          let formattedRe = re.toFixed(3);
          workerPort.postMessage("weight," + formattedRe + "," + zorepoint + "," + overload + "," + flag + "," + wending);
          /*if(flag == 0)
            //this.listData.pushData(`重量计算后内容：${formattedRe}`)
            workerPort.postMessage("weight," + formattedRe + ","+ zorepoint+ ","+ overload+ ","+ flag+ ","+ wending);
          else
            //this.listData.pushData(`重量计算后内容：-${formattedRe}`)
            workerPort.postMessage("-"+formattedRe);*/
        }
        else if (hexString.length == 4)
        {
          //超声波测距 最后返回的单位为米
          let decimal = 0;
          let base = 1;
          for (let index = hexString.length - 1 ; index>=0; index--) {
           let c = hexString.charAt(index);
            let digitValue;
            if (c >= '0' && c <= '9') {
              // 数字字符
              digitValue = c.charCodeAt(0) - '0'.charCodeAt(0);
            } else if (c >= 'a' && c <= 'f') {
              // 小写字母字符
              digitValue = 10 + c.charCodeAt(0) - 'a'.charCodeAt(0);
            } else if (c >= 'A' && c <= 'F') {
              // 大写字母字符
              digitValue = 10 + c.charCodeAt(0) - 'A'.charCodeAt(0);
            } else {
              //throw new Error('Invalid hex character: ' + c);
            }
            decimal += digitValue * base;
            base = base * 16;
          }
          workerPort.postMessage("ranging," + decimal/1000);
        }
        else
        {
          workerPort.postMessage(hexString)
        }
      }
      //}
      console.info('send to main thread===================res=3')
    }
    // 若要停止定时任务，可以调用clearInterval
    if (count >= 5) {
      clearInterval(intervalId);
    }
    //let ddd = new Uint8Array(napi_rfid_checkCard())
  }, 1000); // 每隔1000毫秒执行一次
  console.info('send to main thread===================res=4')


}

/**
 * Defines the event handler to be called when the worker receives a message that cannot be deserialized.
 * The event handler is executed in the worker thread.
 *
 * @param e message data
 */
workerPort.onmessageerror = function (e: MessageEvents) {
}

/**
 * Defines the event handler to be called when an exception occurs during worker execution.
 * The event handler is executed in the worker thread.
 *
 * @param e error message
 */
workerPort.onerror = function (e: ErrorEvent) {
}